#include "xmysql.h"

#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>
#include <QCryptographicHash>
#include <QDateTime>



XMysql::XMysql()
{

}

bool XMysql::connectToDB(QString ip, int port, QString db, QString user, QString password)
{
    if(m_db.isOpen())
    {
        return true;
    }

    qDebug()  << "support driver: " << m_db.drivers();

    m_db = QSqlDatabase::addDatabase("QMYSQL");
    m_db.setHostName(ip);
    m_db.setPort(port);
    m_db.setDatabaseName(db);
    m_db.setUserName(user);
    m_db.setPassword(password);

    bool ret = m_db.open();
    if(!ret)
    {
        qDebug() << "MYSQL Open failed! error: " << m_db.lastError().text();
    }

    return ret;
}

void XMysql::registerUser(Core::User &user)
{
    // 加密密码
    QByteArray tempPswd = QCryptographicHash::hash(user.password.toUtf8(), QCryptographicHash::Sha256);
    QString hashedPassword = tempPswd.toHex();  // 转换为十六进制字符串

    // 创建 SQL 查询字符串
    QSqlQuery query;

    // 插入用户信息到 User 表
    query.prepare("INSERT INTO User (name, gender, birthDate, bio, password) "
                  "VALUES (:name, :gender, :birthDate, :bio, :password)");

    // 绑定参数
    query.bindValue(":name", user.name);
    query.bindValue(":gender", user.gender);
    query.bindValue(":birthDate", user.birthDate);
    query.bindValue(":bio", user.bio);
    query.bindValue(":password", hashedPassword);

    // 执行查询

    if (!query.exec())
    {
        setErrorCode(ErrorCode::UserExist);
        qDebug() << "Error inserting user: " << query.lastError().text();
        return;
    }
    else
    {
        setErrorCode(ErrorCode::NoError);
    }

    qDebug() << "User registered successfully!";

    emit registerFinished(errorCode);
}

void XMysql::updateUser(Core::User &user)
{
    // 创建 SQL 查询字符串
    QSqlQuery query;

    // 插入用户信息到 User 表
    query.prepare("UPDATE User SET gender = :gender, birthDate = :birthDate, bio = :bio WHERE id = :id");

    // 绑定参数
//    query.bindValue(":name", user.name);
    query.bindValue(":gender", user.gender);
    query.bindValue(":birthDate", user.birthDate);
    query.bindValue(":bio", user.bio);
    query.bindValue(":id", user.id);
    // 执行查询

    if (!query.exec())
    {
        setErrorCode(ErrorCode::DBError);
        qDebug() << "Error inserting user: " << query.lastError().text();
        return;
    }
    else
    {
        setErrorCode(ErrorCode::NoError);
        m_currentUser->bio = user.bio;
        m_currentUser->gender = user.gender;
        m_currentUser->birthDate = user.birthDate;
    }

    qDebug() << "User update successfully!";


    emit updateUserFinished(errorCode);
}

void XMysql::login(Core::User &user)
{
    // Step 2: 准备 SQL 查询

    // 加密密码
    QByteArray tempPswd = QCryptographicHash::hash(user.password.toUtf8(), QCryptographicHash::Sha256);
    QString hashedPassword = tempPswd.toHex();  // 转换为十六进制字符串

    QSqlQuery query(m_db);
    query.prepare("SELECT id, name, gender, birthDate, bio FROM User WHERE name = :name AND password = :password");

    // Step 3: 绑定参数
    query.bindValue(":name", user.name);
    query.bindValue(":password", hashedPassword);

    // Step 4: 执行查询
    int ret = 0;
    setErrorCode(ErrorCode::NoError);
    if (!query.exec())
    {
        qDebug() << "Failed to execute query:" << query.lastError().text();
        return;
    }

    // Step 5: 检查查询结果

    if (query.next())
    {
        // 成功匹配用户，将数据库中的信息填充到 User 对象中
        user.id = query.value("id").toInt();
        user.name = query.value("name").toString();
        user.gender = query.value("gender").toString();
        user.birthDate = query.value("birthDate").toString();
        user.bio = query.value("bio").toString();
        qDebug() << "Login successful for user:" << user.name;

        m_currentUser = new Core::User();
        *m_currentUser = user;

        setErrorCode(NoError);
    }
    else
    {
        // 登录失败
        qDebug() << "Login failed: Invalid username or password." << query.lastError().text();
        setErrorCode(ErrorCode::ErrorUserOrPassword);
    }

    emit loginFinished(errorCode);
}

void XMysql::addAnime(Core::Anime &anime)
{
    QSqlQuery query;

    query.prepare("INSERT INTO Anime (title, releaseDate, synopsis, staff, voiceCast, watchLink) "
                  "VALUES (:title, :releaseDate, :synopsis, :staff, :voiceCast, :watchLink)");

    // 绑定数据
    query.bindValue(":title", anime.title);
    query.bindValue(":releaseDate", anime.releaseDate);
    query.bindValue(":synopsis", anime.synopsis);
    query.bindValue(":staff", anime.staff);
    query.bindValue(":voiceCast", anime.voiceCast.join(","));
    query.bindValue(":watchLink", anime.watchLink);

    bool ret = true;
    if (!query.exec())
    {
        ret = false;
        setErrorCode(DBError);
        qDebug() << "Failed to add anime:" << query.lastError().text();
        return;
    }

    // 获取刚插入的 Anime 的 ID
    int animeId = query.lastInsertId().toInt();

    // Step 2: 插入 Tags 表和 Anime_Tags 表
    for (const QString &tag : anime.tags)
    {
        int tagId = -1;

        // 查询标签是否已存在
        QSqlQuery tagQuery;
        tagQuery.prepare("SELECT id FROM Tags WHERE name = :name");
        tagQuery.bindValue(":name", tag);
        if (tagQuery.exec() && tagQuery.next())
        {
            tagId = tagQuery.value(0).toInt();
        }
        else
        {
            setErrorCode(DBError);
            qDebug() << "Failed to add anime:" << query.lastError().text();
            return;
        }

        // 插入 Anime_Tags 表
        QSqlQuery animeTagsQuery;
        animeTagsQuery.prepare("INSERT INTO Anime_Tags (anime_id, tag_id) VALUES (:anime_id, :tag_id)");
        animeTagsQuery.bindValue(":anime_id", animeId);
        animeTagsQuery.bindValue(":tag_id", tagId);

        if (!animeTagsQuery.exec())
        {
            ret = false;
            setErrorCode(DBError);
            qDebug() << "Failed to add anime-tag association:" << animeTagsQuery.lastError().text();
            emit addAnimeFinished(errorCode);
            return;
        }
    }

    setErrorCode(NoError);


    emit addAnimeFinished(errorCode);
}

void XMysql::deleteAnime(Core::Anime &anime)
{
    QSqlQuery query;

    query.prepare("DELETE FROM Anime WHERE id = :id");

    // 绑定数据
    query.bindValue(":id", anime.id);

    bool ret = true;
    if (!query.exec())
    {
        ret = false;
        setErrorCode(DBError);
        qDebug() << "Failed to delete anime:" << query.lastError().text();
    }
    else
    {
        setErrorCode(NoError);
    }

    emit deleteAnimeFinished(errorCode);
}

void XMysql::updateAnime(Core::Anime &anime)
{
    QSqlQuery query;

    query.prepare("UPDATE Anime SET title = :title, releaseDate = :releaseDate, synopsis = :synopsis, "
                  "staff = :staff, voiceCast = :voiceCast, watchLink = :watchLink WHERE id = :id");

    // 绑定数据
    query.bindValue(":title", anime.title);
    query.bindValue(":releaseDate", anime.releaseDate);
    query.bindValue(":synopsis", anime.synopsis);
    query.bindValue(":staff", anime.staff);
    query.bindValue(":voiceCast", anime.voiceCast.join(","));
    query.bindValue(":watchLink", anime.watchLink);
    query.bindValue(":id", anime.id);

    bool ret = true;
    if (!query.exec())
    {
        ret = false;
        setErrorCode(DBError);
        qDebug() << "Failed to update anime:" << query.lastError().text();
    }
    else
    {
        setErrorCode(NoError);
    }

    emit updateAnimeFinished(errorCode);
}

void XMysql::getAnimeByName(QString name)
{
    QSqlQuery query;

    query.prepare("SELECT * FROM Anime WHERE title = :title");
    query.bindValue(":title", name);

    if (!query.exec())
    {
        qDebug() << "Failed to retrieve anime by name:" << query.lastError().text();
        return;
    }

    while (query.next())
    {
        Core::Anime anime;
        anime.id = query.value("id").toInt();
        anime.title = query.value("title").toString();
        anime.releaseDate = query.value("releaseDate").toString();
        anime.synopsis = query.value("synopsis").toString();
        anime.staff = query.value("staff").toString();
        anime.voiceCast = query.value("voiceCast").toString().split(",");
        anime.watchLink = query.value("watchLink").toString();

        // 你可以在这里处理获取的 anime 对象，比如保存到列表或显示
        qDebug() << "Anime Title:" << anime.title;
    }
}

QList<Core::Anime> XMysql::getAllAnimes()
{
    QSqlQuery query;

    QList<Core::Anime> animes;
    bool ret = false;

    // 使用JOIN查询动漫及其评论
    QString sql = R"(
                  SELECT Anime.id, Anime.title, Anime.releaseDate, Anime.synopsis,
                  Anime.staff, Anime.voiceCast, Anime.watchLink,
                  Comment.id AS comment_id, Comment.userId AS comment_userId, Comment.content AS comment_content, Comment.createdAt AS comment_createdAt, User.name AS comment_userName
                  FROM Anime
                  LEFT JOIN Comment ON Anime.id = Comment.animeId LEFT JOIN User ON Comment.userId = User.id ORDER BY Anime.id ASC
                  )";

    if (!query.exec(sql))
    {
        setErrorCode(DBError);
        qDebug() << "Failed to retrieve all animes and comments:" << query.lastError().text();
        return animes;
    }

    // 用于存储当前动漫的评论
    Core::Anime currentAnime;
    int lastAnimeId = -1;

    while (query.next())
    {
        int animeId = query.value("id").toInt();

        // 如果是新的动漫，则将其添加到列表
        if (animeId != lastAnimeId)
        {
            // 如果当前动漫已经有评论，先添加到列表
            if (lastAnimeId != -1)
            {
                animes.append(currentAnime);
            }

            currentAnime = Core::Anime();
            currentAnime.id = animeId;
            currentAnime.title = query.value("title").toString();
            currentAnime.releaseDate = query.value("releaseDate").toString();
            currentAnime.synopsis = query.value("synopsis").toString();
            currentAnime.staff = query.value("staff").toString();
            currentAnime.voiceCast = query.value("voiceCast").toString().split(",");
            currentAnime.watchLink = query.value("watchLink").toString();

            lastAnimeId = animeId;
        }

        // 添加评论到当前动漫的评论列表
        if (query.value("comment_id").toInt() != 0)
        {
            Core::Comment comment;
            comment.id = query.value("comment_id").toInt();
            comment.userId = query.value("comment_userId").toInt();
            comment.userName = query.value("comment_userName").toString();
            comment.content = query.value("comment_content").toString();
            comment.createdAt = query.value("comment_createdAt").toString();

            currentAnime.comments.append(comment);
        }
    }

    // 将最后一个动漫添加到列表
    if (lastAnimeId != -1)
    {
        animes.append(currentAnime);
    }

    // 查询每部动漫的标签列表
    for (auto  &p : animes)
    {
        int animeId = p.id;
        QSqlQuery tagQuery;
        QString tagSql = R"(
            SELECT Tags.name AS tag_name
            FROM Anime_Tags
            JOIN Tags ON Anime_Tags.tag_id = Tags.id
            WHERE Anime_Tags.anime_id = :anime_id
        )";

        tagQuery.prepare(tagSql);
        tagQuery.bindValue(":anime_id", animeId);

        if (!tagQuery.exec())
        {
            setErrorCode(DBError);
            qDebug() << "Failed to retrieve tags for anime ID:" << animeId
                     << tagQuery.lastError().text();
            return animes;
        }

        while (tagQuery.next())
        {
            QString tagName = tagQuery.value("tag_name").toString();
            p.tags.append(tagName);
        }
    }


    setErrorCode(NoError);
    emit getAllAnimeFinished(errorCode, animes);

    return animes;
}

void XMysql::browseByCategory(QString category)
{

}

QList<Core::Anime> XMysql::browseByTag(Core::Filter &filter)
{
    QList<Core::Anime> results;

    // Step 1: 查询 Anime 基本信息
    QString baseQueryStr = R"(
        SELECT DISTINCT a.id, a.title, a.releaseDate, a.synopsis, a.staff, a.voiceCast, a.watchLink
        FROM Anime a
        LEFT JOIN Anime_Tags at ON a.id = at.anime_id
        LEFT JOIN Tags t ON at.tag_id = t.id
    )";

    QStringList conditions;
    QStringList tags = filter.tag;
    QStringList years = filter.year;
    // 添加标签条件
    if (!tags.isEmpty())
    {
        QStringList tagConditions;
        for (int i = 0; i < tags.size(); ++i)
        {
            tagConditions.append(QString("t.name = :tag%1").arg(i));
        }
        conditions.append("(" + tagConditions.join(" OR ") + ")");
    }

    // 添加年份条件
    if (!years.isEmpty())
    {
        QStringList yearConditions;
        for (int i = 0; i < years.size(); ++i)
        {
            yearConditions.append(QString("a.releaseDate LIKE :year%1").arg(i));
        }
        conditions.append("(" + yearConditions.join(" OR ") + ")");
    }

    if (!conditions.isEmpty())
    {
        baseQueryStr += " WHERE " + conditions.join(" AND ");
    }

//    baseQueryStr += " ORDER BY a.releaseDate DESC";

    QSqlQuery baseQuery;
    baseQuery.prepare(baseQueryStr);

    // 绑定标签参数
    for (int i = 0; i < tags.size(); ++i)
    {
        baseQuery.bindValue(QString(":tag%1").arg(i), tags.at(i));
    }

    // 绑定年份参数
    for (int i = 0; i < years.size(); ++i)
    {
        baseQuery.bindValue(QString(":year%1").arg(i), years.at(i) + "%");
    }

    if (!baseQuery.exec())
    {
        qWarning() << "Failed to query Anime:" << baseQuery.lastError().text();
        return results;
    }

    // Step 2: 填充 Anime 基本信息
    QMap<int, Core::Anime> animeMap;
    while (baseQuery.next())
    {
        int id = baseQuery.value("id").toInt();
        Core::Anime anime;
        anime.id = id;
        anime.title = baseQuery.value("title").toString();
        anime.releaseDate = baseQuery.value("releaseDate").toString();
        anime.synopsis = baseQuery.value("synopsis").toString();
        anime.staff = baseQuery.value("staff").toString();
        anime.voiceCast = baseQuery.value("voiceCast").toString().split(",");
        anime.watchLink = baseQuery.value("watchLink").toString();

        animeMap[id] = anime;
    }

    if (animeMap.isEmpty())
    {
        return results;
    }

    // Step 3: 查询 Tags
    QString tagQueryStr = R"(
        SELECT at.anime_id, t.name
        FROM Anime_Tags at
        JOIN Tags t ON at.tag_id = t.id
        WHERE at.anime_id IN (%1)
    )";
    QStringList animeIds;
    for (int id : animeMap.keys())
    {
        animeIds.append(QString::number(id));
    }
    tagQueryStr = tagQueryStr.arg(animeIds.join(","));

    QSqlQuery tagQuery(tagQueryStr);
    if (!tagQuery.exec())
    {
        qWarning() << "Failed to query Tags:" << tagQuery.lastError().text();
        return results;
    }

    while (tagQuery.next())
    {
        int animeId = tagQuery.value("anime_id").toInt();
        QString tag = tagQuery.value("name").toString();
        if (animeMap.contains(animeId))
        {
            animeMap[animeId].tags.append(tag);
        }
    }

    // Step 3: 查询 Comments
    QString commentQueryStr = R"(
           SELECT c.id, c.animeId, c.userId, u.name, c.content, c.createdAt
           FROM Comment c
           JOIN User u ON c.userId = u.id
           WHERE c.animeId IN (%1)
       )";


    commentQueryStr = commentQueryStr.arg(animeIds.join(","));

    QSqlQuery commentQuery(commentQueryStr);
    if (!commentQuery.exec())
    {
        qWarning() << "Failed to query Comments:" << commentQuery.lastError().text();
        return results;
    }

    while (commentQuery.next())
    {
        int animeId = commentQuery.value("animeId").toInt();
        Core::Comment comment;
        comment.id = commentQuery.value("id").toInt();
        comment.animeId = animeId;
        comment.userId = commentQuery.value("userId").toInt();
        comment.userName = commentQuery.value("name").toString();
        comment.content = commentQuery.value("content").toString();
        comment.createdAt = commentQuery.value("createdAt").toString();

        if (animeMap.contains(animeId))
        {
            animeMap[animeId].comments.append(comment);
        }
    }

    // Step 5: 转换到结果列表
    results = animeMap.values();

    getFilterAnimeFinished(errorCode, results);

    return results;
}

void XMysql::commentAnime(Core::Comment &comment)
{
    // Step 1: 创建 SQL 插入语句
    QSqlQuery query;
    query.prepare("INSERT INTO PendingComment (animeId, userId, content, createdAt) "
                  "VALUES (:animeId, :userId, :content, :createdAt)");

    // Step 2: 绑定参数
    query.bindValue(":animeId", comment.animeId);  // 绑定动漫ID
    query.bindValue(":userId", comment.userId);    // 绑定用户ID
    query.bindValue(":content", comment.content);  // 绑定评论内容
    query.bindValue(":createdAt", QDateTime::currentDateTime().toString(DATETIME_FORMAT));  // 绑定评论时间

    // Step 3: 执行插入操作
    if (!query.exec())
    {
        setErrorCode(DBError);
        qWarning() << "Failed to insert comment for animeId:" << comment.animeId;
        return;
    }

    qDebug() << "Successfully inserted comment for animeId:" << comment.animeId;

    setErrorCode(NoError);
    emit commentFinished(errorCode);
}

void XMysql::acceptComment(Core::Comment &comment)
{
    QSqlQuery query(m_db);
    m_db.transaction(); // 开启事务
    // 插入到 Comment 表
    query.prepare(R"(
                  INSERT INTO Comment (animeId, userId, content, createdAt)
                  SELECT animeId, userId, content, createdAt FROM PendingComment WHERE id = :id
                  )");
    query.bindValue(":id", comment.id);
    if (!query.exec())
    {
        setErrorCode(DBError);
        m_db.rollback(); // 回滚事务
        return;
    }

    // 删除 PendingComment 中对应的记录
    query.prepare("DELETE FROM PendingComment WHERE id = :id");
    query.bindValue(":id", comment.id);
    if (!query.exec())
    {
        setErrorCode(DBError);
        m_db.rollback(); // 回滚事务
        return;
    }

    setErrorCode(NoError);
    m_db.commit(); // 提交事务
    qDebug() << "Comment approved and moved to Comment table: ID =" << comment.id;
}

void XMysql::rejectComment(Core::Comment &comment)
{
    QSqlQuery query(m_db);

    // 更新 PendingComment 状态为 rejected
    query.prepare("UPDATE PendingComment SET status = 'rejected' WHERE id = :id");
    query.bindValue(":id", comment.id);
    if (!query.exec())
    {
        setErrorCode(DBError);
        return;
    }
    qDebug() << "Comment rejected: ID =" << comment.id;
}


QList<Core::Comment> XMysql::getPendingComment()
{
    QSqlQuery query(m_db);

    QList<Core::Comment> comments;
    // 查询 PendingComment 表中状态为 'pending' 的记录
    QString sql = R"(
            SELECT pc.id, pc.animeId, pc.userId, u.name AS userName, pc.content, pc.createdAt
            FROM PendingComment pc
            JOIN User u ON pc.userId = u.id
            WHERE pc.status = 'pending'
        )";

    if (!query.exec(sql) )
    {
        qCritical() << "Failed to fetch pending comments:" << query.lastError().text();
        return comments;
    }

    // 遍历查询结果，构建 Comment 对象并添加到列表中
    while (query.next())
    {
        Core::Comment comment;
        comment.id = query.value(0).toInt();
        comment.animeId = query.value(1).toInt();
        comment.userId = query.value(2).toInt();
        comment.userName = query.value(3).toString();
        comment.content = query.value(4).toString();
        comment.createdAt = query.value(5).toString();

        comments.append(comment);
    }

    qDebug() << "Fetched" << comments.size() << "pending comments.";
    return comments;
}

void XMysql::post(Core::Post &post)
{
    QSqlQuery query(m_db);
    query.prepare("INSERT INTO PendingPost (userId, title, content, createdAt) "
                  "VALUES (:userId, :title, :content, :createdAt)");

    // Step 3: 绑定参数
    query.bindValue(":userId", m_currentUser->id);
    query.bindValue(":title", post.title);
    query.bindValue(":content", post.content);
    query.bindValue(":createdAt", QDateTime::currentDateTime().toString(DATETIME_FORMAT));

    // Step 4: 执行查询
    if (!query.exec())
    {
        setErrorCode(DBError);
        qDebug() << "Failed to insert post:" << query.lastError().text();
        return ;
    }

    // Step 5: 获取生成的帖子 ID
    int postId = query.lastInsertId().toInt();

    // Step 6: 构造 Post 对象
    //    Post newPost(postId, userId, title, content, QDateTime::currentDateTime().toString(Qt::ISODate));

    qDebug() << "Post created successfully with ID:" << postId;
    setErrorCode(NoError);

    emit postFinished(errorCode);
}

QList<Core::Post> XMysql::getPosts(int cnt)
{
    QList<Core::Post> posts;

    // Step 1: 检查数据库连接
    if (!m_db.isOpen())
    {
        qDebug() << "Database is not open.";
        return posts;
    }

    // Step 2: 执行 SQL 查询获取最新的十条帖子
    QSqlQuery query(m_db);
    query.prepare("SELECT Post.id AS post_id, Post.userId AS post_userId, Post.title AS post_title, "
                  "Post.content AS post_content, Post.createdAt AS post_createdAt, Post.likeCount AS post_likeCount, Post.userLiked AS post_userLiked, "
                  "User.name AS post_userName, PostComment.id AS comment_id, PostComment.postId AS comment_postId, PostComment.userId AS comment_userId, "
                  "PostComment.content AS comment_content, PostComment.createdAt AS comment_createdAt, CommentUser.name AS comment_userName, "
                  "PostLike.userId AS like_userId "
                  "FROM Post "
                  "JOIN User ON Post.userId = User.id "
                  "LEFT JOIN PostComment ON Post.id = PostComment.postId "
                  "LEFT JOIN User AS CommentUser ON PostComment.userId = CommentUser.id "
                  "LEFT JOIN PostLike ON Post.id = PostLike.postId "
                  "ORDER BY Post.createdAt DESC");

    //     query.prepare(QString("SELECT id, userId, title, content, createdAt, likeCount, userLiked FROM Post "
    //                   "ORDER BY createdAt DESC LIMIT %1").arg(cnt));

    if (!query.exec())
    {
        setErrorCode(DBError);
        qDebug() << "Failed to execute query:" << query.lastError().text();

        return posts;
    }

    // 用于临时存储 Post 对象的哈希表
    QHash<int, Core::Post> postMap;

    // 遍历查询结果
    Core::Post currentPost;
    int lastPostId = -1;
    QSet<int> addedComments; // 用于去重评论
    QSet<int> addedLikes;    // 用于去重点赞
    while (query.next())
    {
        int postId = query.value("post_id").toInt();

        // 如果帖子不存在于 map 中，创建一个新的帖子对象
        if (postId != lastPostId)
        {
            // 在已有的帖子不为空时，将当前帖子添加到 posts 列表中
            if (lastPostId != -1)
            {
                posts.append(currentPost);
            }

            // 根据查询结果填充 currentPost 的属性
            currentPost = Core::Post();
            currentPost.id = postId;
            currentPost.userId = query.value("post_userId").toInt();
            currentPost.userName = query.value("post_userName").toString();
            currentPost.title = query.value("post_title").toString();
            currentPost.content = query.value("post_content").toString();
            currentPost.createdAt = query.value("post_createdAt").toString();
            currentPost.likeCount = query.value("post_likeCount").toInt();
            currentPost.userLiked = query.value("post_userLiked").toBool();

            // 清空评论和点赞的去重集合
            addedComments.clear();
            addedLikes.clear();

            lastPostId = postId;
        }

        // 获取评论信息并将其添加到 currentPost 中
        int commentId = query.value("comment_id").toInt();
        if (commentId != 0 && !addedComments.contains(commentId))   // 如果有评论且评论ID未添加过
        {
            Core::PostComment comment(
                commentId,
                query.value("comment_postId").toInt(),
                query.value("comment_userId").toInt(),
                query.value("comment_content").toString(),
                query.value("comment_createdAt").toString()
            );
            comment.userName = query.value("comment_userName").toString();
            currentPost.comments.append(comment); // 将评论添加到 currentPost 中
            addedComments.insert(commentId); // 标记评论ID已添加
        }

        // 获取点赞信息并将其添加到 currentPost 的 likes 中
        int likeUserId = query.value("like_userId").toInt();
        if (likeUserId != 0 && !addedLikes.contains(likeUserId))   // 如果有点赞记录且用户未点赞过
        {
            Core::LikePost like(
                0, // 点赞记录 ID（可以根据需要生成）
                postId,
                likeUserId,
                query.value("comment_createdAt").toString() // 点赞时间，这里可以使用评论时间，假设点赞和评论时间相同
            );
            currentPost.likes.append(like); // 将点赞信息添加到 currentPost 中
            addedLikes.insert(likeUserId); // 标记点赞用户ID已添加
        }
    }

    // 将最后一个动漫添加到列表
    if (lastPostId != -1)
    {
        posts.append(currentPost);
    }


    setErrorCode(NoError);
    emit getAllPostsFinished(errorCode, posts);
    return posts;

}

void XMysql::acceptpost(Core::Post &post)
{
    QSqlQuery query(m_db);
    query.prepare("INSERT INTO Post (userId, title, content, createdAt, likeCount, userLiked) "
                  "VALUES (:userId, :title, :content, :createdAt, 0, false)");

    // Step 3: 绑定参数
    query.bindValue(":userId", post.userId);
    query.bindValue(":title", post.title);
    query.bindValue(":content", post.content);
    query.bindValue(":createdAt", post.createdAt);

    // Step 4: 执行查询
    if (!query.exec())
    {
        setErrorCode(DBError);
        qDebug() << "Failed to insert post:" << query.lastError().text();
        return ;
    }

    // 更新 PendingComment 状态为 approved
    query.prepare("UPDATE PendingPost SET status = 'approved' WHERE id = :id");
    query.bindValue(":id", post.id);
    if (!query.exec())
    {
        setErrorCode(DBError);
        return;
    }

    // Step 5: 获取生成的帖子 ID
    int postId = query.lastInsertId().toInt();

    // Step 6: 构造 Post 对象
    //    Post newPost(postId, userId, title, content, QDateTime::currentDateTime().toString(Qt::ISODate));

    qDebug() << "Post created successfully with ID:" << postId;
    setErrorCode(NoError);
    emit postFinished(errorCode);
}

void XMysql::rejectpost(Core::Post &post)
{
    QSqlQuery query(m_db);

    // 更新 PendingComment 状态为 rejected
    query.prepare("UPDATE PendingPost SET status = 'rejected' WHERE id = :id");
    query.bindValue(":id", post.id);
    if (!query.exec())
    {
        setErrorCode(DBError);
        return;
    }
    qDebug() << "post rejected: ID =" << post.id;
}

QList<Core::Post> XMysql::getPendingPost()
{
    QList<Core::Post> pendingPosts;

    // 创建数据库查询对象
    QSqlQuery query(m_db);

    // SQL 查询语句
    QString sql = "SELECT PendingPost.id, PendingPost.userId, User.name, PendingPost.title, PendingPost.content,PendingPost.createdAt "
                  "FROM PendingPost "
                  "LEFT JOIN User ON PendingPost.userId = User.id "
                  "WHERE PendingPost.status = 'pending'";

    // 执行查询
    if (!query.exec(sql))
    {
        qWarning() << "Failed to execute query:" << query.lastError().text();
        return pendingPosts;
    }

    // 解析查询结果
    while (query.next())
    {
        int id = query.value("id").toInt();
        int userId = query.value("userId").toInt();
        QString userName = query.value("name").toString();
        QString title = query.value("title").toString();
        QString content = query.value("content").toString();

        Core::Post post(id, userId, userName, title, content, "", 0, false);
        post.createdAt = query.value("createdAt").toString();

        // 将帖子添加到列表中
        pendingPosts.append(post);
    }

    return pendingPosts;
}

void XMysql::postComment(Core::PostComment &comment)
{
    // Step 1: 检查传入的评论数据是否有效
    if (comment.content.isEmpty() )
    {
        qWarning() << "Invalid comment data!";
        return;
    }

    // Step 2: 构建 SQL 查询字符串
    QString queryStr = "INSERT INTO PostComment (postId, userId, content, createdAt) "
                       "VALUES (:postId, :userId, :content, :createdAt)";

    // Step 3: 使用 QSqlQuery 和 bindValue 进行插入操作
    QSqlQuery query;
    query.prepare(queryStr);

    // 绑定参数
    query.bindValue(":postId", comment.postId);
    query.bindValue(":userId", comment.userId);
    query.bindValue(":content", comment.content);
    query.bindValue(":createdAt", QDateTime::currentDateTime().toString(DATETIME_FORMAT));

    // Step 4: 执行 SQL 查询
    if (!query.exec())
    {
        setErrorCode(DBError);
        qWarning() << "Failed to insert comment:" << query.lastError().text();
        return;
    }

    setErrorCode(NoError);
    // Step 5: 获取插入的评论 ID（如果需要）
    comment.id = query.lastInsertId().toInt();

    qDebug() << "Comment inserted with ID:" << comment.id;
    emit postCommentFinished(errorCode);
}

void XMysql::likePost(Core::LikePost &likePost)
{
    // Step 1: 插入点赞记录到 Like 表
    QSqlQuery query;
    query.prepare("INSERT INTO PostLike (postId, userId, likedAt) "
                  "VALUES (:postId, :userId, :likedAt)");

    // 绑定参数
    query.bindValue(":postId", likePost.postId);
    query.bindValue(":userId", likePost.userId);
    query.bindValue(":likedAt", QDateTime::currentDateTime().toString(DATETIME_FORMAT));

    // Step 2: 执行插入点赞记录的查询
    if (!query.exec())
    {
        setErrorCode(DBError);
        qWarning() << "Failed to insert like record for postId:" << likePost.postId
                   << "userId:" << likePost.userId << query.lastError().text();
        return;
    }

    // Step 3: 更新帖子点赞数
    query.prepare("UPDATE Post SET likeCount = likeCount + 1 WHERE id = :postId");

    // 绑定帖子ID
    query.bindValue(":postId", likePost.postId);

    // 执行更新查询
    if (!query.exec())
    {
        setErrorCode(DBError);
        qWarning() << "Failed to update likeCount for postId:" << likePost.postId;
        return;
    }

    // Step 4: 成功执行
    setErrorCode(NoError);
    qDebug() << "Successfully updated likeCount for postId:" << likePost.postId;
    emit likePostFinished(errorCode);
}
